﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Account;
using TomNet.IMSC.Model.DbModels.Account;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;
using TomNet.IMSC.Model.ViewModels.Account;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Core.Contracts.LowPriceHouse;
using TomNet.IMSC.Core.Contracts.Decoration;
using TomNet.IMSC.Core.Contracts.Finance;
using TomNet.IMSC.Web.Filters;

namespace TomNet.IMSC.Web.Areas.Account.Controllers
{
    [Description("财务-费用")]
    public class ExpensesController : BaseController
    {


        public IExpensesRunningsContract EContract { set; get; }// 费用流水
        public IStaffContract SContract { get; set; }
        public INewHouseRunningsContract NHContract { get; set; }
        public ILowPriceHouseRunningsContract LPHContract { get; set; }
        public IDecorationRunningsContract DContract { get; set; }
        public IFinanceRunningsContract FContract { get; set; }
        // GET: Account/Expenses
        [Description("财务-费用列表面页")]
        [GlobalAuthorization]
        public ActionResult ExpensesList(int ModuleID, int RunningsID = 0)
        {
            ViewBag.ModuleID = ModuleID;
            ViewBag.RunningsID = RunningsID;
            return View();
        }

        [Description("财务-获得费用列表数据")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult GetExpensesList(int pageIndex, int pageSize, int ModuleID, int RunningsID, int State, string Search)//, string search = "", int depid
        {
            IQueryable<ExpensesListModel> query = Enumerable.Empty<ExpensesListModel>().AsQueryable();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            switch (ModuleID)
            {
                case 1:
                    query = from e in EContract.Entities
                            join n in NHContract.Entities on e.RunningsID equals n.Id
                            join u1 in SContract.Entities on e.ConfirmStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on e.AuditingStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on e.RemittanceStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            select new ExpensesListModel
                            {
                                Amount = e.Amount,
                                AuditingRemark = e.AuditingRemark,
                                AuditingStaffID = e.AuditingStaffID,
                                AuditingStaffName = eu2d.Name,
                                AuditingTime = e.AuditingTime,
                                ConfirmStaffID = e.ConfirmStaffID,
                                ConfirmStaffName = eu1d.Name,
                                ConfirmTime = e.ConfirmTime,
                                Id = e.Id,
                                ModuleID = e.ModuleID,
                                Remark = e.Remark,
                                RemittanceAccount = e.RemittanceAccount,
                                RemittanceBank = e.RemittanceBank,
                                RemittanceName = e.RemittanceName,
                                RemittanceStaffID = e.RemittanceStaffID,
                                RemittanceStaffName = eu3d.Name,
                                RemittanceTime = e.RemittanceTime,
                                RunningsID = e.RunningsID,
                                State = e.State,
                                IntermediaryName=n.IntermediaryName,
                                ItemName=n.BuildingName,
                                CustomerName = n.CustomerName,
                                CustomerPhone=n.CustomerPhone,
                                UserName=n.UserName,
                                AgentID=n.AgentID
                                
                            };
                    break;
                case 2:
                case 3:
                    query = from e in EContract.Entities
                            join n in LPHContract.Entities on e.RunningsID equals n.Id
                            join u1 in SContract.Entities on e.ConfirmStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on e.AuditingStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on e.RemittanceStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            select new ExpensesListModel
                            {
                                Amount = e.Amount,
                                AuditingRemark = e.AuditingRemark,
                                AuditingStaffID = e.AuditingStaffID,
                                AuditingStaffName = eu2d.Name,
                                AuditingTime = e.AuditingTime,
                                ConfirmStaffID = e.ConfirmStaffID,
                                ConfirmStaffName = eu1d.Name,
                                ConfirmTime = e.ConfirmTime,
                                Id = e.Id,
                                ModuleID = e.ModuleID,
                                Remark = e.Remark,
                                RemittanceAccount = e.RemittanceAccount,
                                RemittanceBank = e.RemittanceBank,
                                RemittanceName = e.RemittanceName,
                                RemittanceStaffID = e.RemittanceStaffID,
                                RemittanceStaffName = eu3d.Name,
                                RemittanceTime = e.RemittanceTime,
                                RunningsID = e.RunningsID,
                                State = e.State,
                                IntermediaryName = n.IntermediaryName,
                                ItemName = n.BuildingName,
                                CustomerName = n.CustomerName,
                                CustomerPhone = n.CustomerPhone,
                                UserName = n.UserName,
                                AgentID = n.AgentID
                            };
                    break;
                case 4:
                    query = from e in EContract.Entities
                            join n in DContract.Entities on e.RunningsID equals n.Id
                            join u1 in SContract.Entities on e.ConfirmStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on e.AuditingStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on e.RemittanceStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            select new ExpensesListModel
                            {
                                Amount = e.Amount,
                                AuditingRemark = e.AuditingRemark,
                                AuditingStaffID = e.AuditingStaffID,
                                AuditingStaffName = eu2d.Name,
                                AuditingTime = e.AuditingTime,
                                ConfirmStaffID = e.ConfirmStaffID,
                                ConfirmStaffName = eu1d.Name,
                                ConfirmTime = e.ConfirmTime,
                                Id = e.Id,
                                ModuleID = e.ModuleID,
                                Remark = e.Remark,
                                RemittanceAccount = e.RemittanceAccount,
                                RemittanceBank = e.RemittanceBank,
                                RemittanceName = e.RemittanceName,
                                RemittanceStaffID = e.RemittanceStaffID,
                                RemittanceStaffName = eu3d.Name,
                                RemittanceTime = e.RemittanceTime,
                                RunningsID = e.RunningsID,
                                State = e.State,
                                IntermediaryName = n.IntermediaryName,
                                ItemName = n.DecorationCompanyName,
                                CustomerName = n.CustomerName,
                                CustomerPhone = n.CustomerPhone,
                                UserName = n.UserName,
                                AgentID = n.AgentID
                            };
                    break;
                case 5:
                    query = from e in EContract.Entities
                            join n in FContract.Entities on e.RunningsID equals n.Id
                            join u1 in SContract.Entities on e.ConfirmStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on e.AuditingStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on e.RemittanceStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            select new ExpensesListModel
                            {
                                Amount = e.Amount,
                                AuditingRemark = e.AuditingRemark,
                                AuditingStaffID = e.AuditingStaffID,
                                AuditingStaffName = eu2d.Name,
                                AuditingTime = e.AuditingTime,
                                ConfirmStaffID = e.ConfirmStaffID,
                                ConfirmStaffName = eu1d.Name,
                                ConfirmTime = e.ConfirmTime,
                                Id = e.Id,
                                ModuleID = e.ModuleID,
                                Remark = e.Remark,
                                RemittanceAccount = e.RemittanceAccount,
                                RemittanceBank = e.RemittanceBank,
                                RemittanceName = e.RemittanceName,
                                RemittanceStaffID = e.RemittanceStaffID,
                                RemittanceStaffName = eu3d.Name,
                                RemittanceTime = e.RemittanceTime,
                                RunningsID = e.RunningsID,
                                State = e.State,
                                IntermediaryName = n.IntermediaryName,
                                ItemName = n.FinanceItemsName,
                                CustomerName = n.CustomerName,
                                CustomerPhone = n.CustomerPhone,
                                UserName = n.UserName,
                                AgentID = n.AgentID
                            };
                    break;
                default:
                    break;
            }
            query = query.Where(p => p.ModuleID == ModuleID);
            if (model.AgentId>0)
            {
                query = query.Where(p => p.AgentID == model.AgentId);
            }
            //数据总数
            if (RunningsID > 0)
            {
                query = query.Where(p => p.RunningsID == RunningsID);
            }
            if (State > 0)// 状态  1待审核    2已审核    3审核未通过    4已出款
            {
                query = query.Where(p => p.State == State);
            }
            if (!String.IsNullOrEmpty(Search))
            {
                query = query.Where(p => p.Remark.IndexOf(Search) != -1 || p.ItemName.IndexOf(Search) != -1 || p.IntermediaryName.IndexOf(Search) != -1 || p.UserName.IndexOf(Search) != -1 || p.CustomerName.IndexOf(Search) != -1 || p.CustomerPhone.IndexOf(Search) != -1);
            }

            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : null;

            GridData<object> gridData = total > 0 ? new GridData<object>() { Total = total, Rows = query.ToList() } : new GridData<object>() { Total = total, Rows = new List<string>() };

            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        [Description("财务-费用添加面页")]
        [GlobalAuthorization]
        public ActionResult AddExpenses(int ModuleID, int RunningsID)
        {
            ViewBag.ModuleID = ModuleID;
            ViewBag.RunningsID = RunningsID;
            return View();
        }
        [Description("财务-添加费用")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult AddExpensesAsync(ExpensesRunnings entity)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            try
            {
                entity.AuditingRemark = "";
                entity.AuditingStaffID = 0;
                entity.AuditingTime = DateTime.Now;
                entity.ConfirmStaffID = model.Id;
                entity.ConfirmTime = DateTime.Now;
                entity.RemittanceAccount = "";
                entity.RemittanceBank = "";
                entity.RemittanceStaffID = 0;
                entity.RemittanceTime = DateTime.Now;
                entity.State = 1;
                var count = EContract.Insert(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "录入成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "录入失败";
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        [Description("财务-费用审核面页")]
        [GlobalAuthorization]
        public ActionResult AuditingExpenses(int ID)
        {
            ViewBag.ID = ID;
            return View();
        }
        [Description("财务-审核费用")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult AuditingExpensesAsync(ExpensesRunnings entity)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            try
            {
                var query = EContract.CheckExists(m => m.Id.Equals(entity.Id));
                if (!query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "不存在对应费用";
                }
                else
                {
                    var e = EContract.GetByKey(entity.Id);
                    e.State = entity.State;
                    e.AuditingRemark = String.IsNullOrEmpty(entity.Remark) ? "" : entity.Remark;
                    e.AuditingTime = DateTime.Now;
                    e.AuditingStaffID = model.Id;
                    var count = EContract.Update(e);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "操作成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "操作失败";
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        [Description("财务-费用出款面页")]
        [GlobalAuthorization]
        public ActionResult ExpensesRemittance(int ID)
        {
            ViewBag.ID = ID;
            return View();
        }
        [Description("财务-审核费用")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult ExpensesRemittanceAsync(ExpensesRunnings entity)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            try
            {
                var query = EContract.CheckExists(m => m.Id.Equals(entity.Id));
                if (!query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "不存在对应费用";
                }
                else
                {
                    var e = EContract.GetByKey(entity.Id);
                    e.State = 4;
                    e.RemittanceBank = entity.RemittanceBank;
                    e.RemittanceName = entity.RemittanceName;
                    e.RemittanceAccount = entity.RemittanceAccount;
                    e.RemittanceTime = DateTime.Now;
                    e.RemittanceStaffID = model.Id;
                    var count = EContract.Update(e);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "操作成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "操作失败";
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

    }
}